import React, { useState, useEffect } from 'react'
import {
  Card,
  Progress,
  Space,
  Button,
  Typography,
  Tag,
  Alert,
  Timeline,
  Tooltip,
  Spin,
} from 'antd'
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
} from '@ant-design/icons'
import { formatDuration } from '@/utils'

const { Text, Title } = Typography

export interface ExecutionStatus {
  id: string
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'
  progress?: number
  message?: string
  start_time?: string
  end_time?: string
  duration?: number
  error?: string
  stages?: Array<{
    name: string
    status: 'pending' | 'running' | 'completed' | 'failed'
    start_time?: string
    end_time?: string
    duration?: number
    message?: string
  }>
}

interface ExecutionProgressProps {
  execution: ExecutionStatus | null
  onCancel?: () => void
  onRetry?: () => void
  showStages?: boolean
  compact?: boolean
}

const ExecutionProgress: React.FC<ExecutionProgressProps> = ({
  execution,
  onCancel,
  onRetry,
  showStages = true,
  compact = false,
}) => {
  const [elapsedTime, setElapsedTime] = useState(0)

  // 计算执行时间
  useEffect(() => {
    if (!execution || execution.status !== 'running') {
      return
    }

    const startTime = execution.start_time ? new Date(execution.start_time).getTime() : Date.now()
    
    const timer = setInterval(() => {
      setElapsedTime(Date.now() - startTime)
    }, 100)

    return () => clearInterval(timer)
  }, [execution?.status, execution?.start_time])

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return <ClockCircleOutlined style={{ color: '#faad14' }} />
      case 'running':
        return <LoadingOutlined style={{ color: '#1890ff' }} />
      case 'completed':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />
      case 'failed':
        return <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />
      case 'cancelled':
        return <StopOutlined style={{ color: '#d9d9d9' }} />
      default:
        return <ClockCircleOutlined />
    }
  }

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'warning'
      case 'running':
        return 'processing'
      case 'completed':
        return 'success'
      case 'failed':
        return 'error'
      case 'cancelled':
        return 'default'
      default:
        return 'default'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '等待执行'
      case 'running':
        return '正在执行'
      case 'completed':
        return '执行完成'
      case 'failed':
        return '执行失败'
      case 'cancelled':
        return '已取消'
      default:
        return '未知状态'
    }
  }

  if (!execution) {
    return null
  }

  const isRunning = execution.status === 'running'
  const canCancel = isRunning
  const canRetry = execution.status === 'failed'
  const displayDuration = execution.duration || elapsedTime

  if (compact) {
    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        gap: 8,
        padding: '8px 12px',
        background: '#f5f5f5',
        borderRadius: 6,
      }}>
        {getStatusIcon(execution.status)}
        <Text style={{ fontSize: 12 }}>
          {getStatusText(execution.status)}
        </Text>
        {displayDuration > 0 && (
          <Text type="secondary" style={{ fontSize: 11 }}>
            {formatDuration(displayDuration)}
          </Text>
        )}
        {canCancel && (
          <Button 
            type="text" 
            size="small" 
            icon={<StopOutlined />}
            onClick={onCancel}
            style={{ padding: '0 4px' }}
          />
        )}
      </div>
    )
  }

  return (
    <Card size="small" style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ flex: 1 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            {/* 状态标题 */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {getStatusIcon(execution.status)}
              <Text strong>{getStatusText(execution.status)}</Text>
              <Tag color={getStatusColor(execution.status)}>
                {execution.status.toUpperCase()}
              </Tag>
              {displayDuration > 0 && (
                <Text type="secondary">
                  {formatDuration(displayDuration)}
                </Text>
              )}
            </div>

            {/* 进度条 */}
            {isRunning && execution.progress !== undefined && (
              <Progress
                percent={execution.progress}
                status="active"
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
            )}

            {/* 消息 */}
            {execution.message && (
              <Text type="secondary" style={{ fontSize: 12 }}>
                {execution.message}
              </Text>
            )}

            {/* 错误信息 */}
            {execution.error && (
              <Alert
                message="执行错误"
                description={execution.error}
                type="error"
                showIcon
                style={{ marginTop: 8 }}
              />
            )}

            {/* 执行阶段 */}
            {showStages && execution.stages && execution.stages.length > 0 && (
              <div style={{ marginTop: 16 }}>
                <Text strong style={{ fontSize: 12, marginBottom: 8, display: 'block' }}>
                  执行阶段：
                </Text>
                <Timeline size="small">
                  {execution.stages.map((stage, index) => (
                    <Timeline.Item
                      key={index}
                      dot={getStatusIcon(stage.status)}
                      color={getStatusColor(stage.status)}
                    >
                      <div>
                        <Text style={{ fontSize: 12 }}>{stage.name}</Text>
                        {stage.duration && (
                          <Text type="secondary" style={{ fontSize: 11, marginLeft: 8 }}>
                            ({formatDuration(stage.duration)})
                          </Text>
                        )}
                        {stage.message && (
                          <div style={{ fontSize: 11, color: '#666', marginTop: 2 }}>
                            {stage.message}
                          </div>
                        )}
                      </div>
                    </Timeline.Item>
                  ))}
                </Timeline>
              </div>
            )}
          </Space>
        </div>

        {/* 操作按钮 */}
        <Space>
          {canCancel && (
            <Tooltip title="取消执行">
              <Button
                type="text"
                danger
                icon={<StopOutlined />}
                onClick={onCancel}
              >
                取消
              </Button>
            </Tooltip>
          )}
          
          {canRetry && (
            <Tooltip title="重新执行">
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={onRetry}
              >
                重试
              </Button>
            </Tooltip>
          )}
        </Space>
      </div>
    </Card>
  )
}

export default ExecutionProgress